package simframe.util;

import java.util.Vector;
import java.util.Iterator;

/*
 * Given a list of objects 
 */

public class Bucket<E> implements Iterable<E> {
	
	public class BucketIterator implements Iterator<E> {

		int numDraws = 0;
		
		/*
		 * This is the list if indices that have been swapped or used already
		 * The indices are the actual index + 1 so that
		 * the initialized array of all zeros represents nothing swapped
		 */
		int[] drawList = new int[list.size()];
		
		public boolean hasNext() {
			return numDraws < list.size();
		}

		public E next() {

			Double rindex = Math.floor((list.size() - numDraws) * Math.random());

			int index = rindex.intValue();

			if ( index > 0) {

				// swap numDraws with numDraws + index;
				// values already drawn --  -- not yet drawn 
				// 12 13 77 34 19 3 2 99  0

				int tmp;
				if (drawList[numDraws] == 0)
					tmp = numDraws + 1;
				else
					tmp = drawList[numDraws];

				if (drawList[numDraws + index] == 0) {
					// this was never swapped TO
					drawList[numDraws] = numDraws + index + 1;
					drawList[numDraws + index] = tmp;
				}
				else
				{
					// this was swapped to at some point
					// just swap again
					drawList[numDraws] = drawList[numDraws + index];
					drawList[numDraws + index] = tmp;
				}
			}
			else if (drawList[numDraws] == 0) {
				// no swap
				drawList[numDraws] = numDraws + 1;
			}
			
			// revert back to 0 - based indexing
			int selectIndex = drawList[numDraws] - 1;
			
			numDraws++;

			return list.get(selectIndex);
		}

		public void remove() {
		
		}
	}
	
	private Vector<E> list = new Vector<E>();
	
	public void add(E item) {
		list.add(item);
	}

	public Iterator<E> iterator() {
		// when the iterator is called we initialize the bucket
		return new BucketIterator();
	}
	
	public int size() {
		return list.size();
	}

}
